package com.bwie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.LoginConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.Menu;
import com.bwie.common.domain.User;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.exception.MenuException;
import com.bwie.mapper.MenuMapper;
import com.bwie.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @className: MenuServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 张雨乐
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    HttpServletRequest request;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MenuMapper menuMapper;
    @Override
    public Result role(String id) {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (user==null){
            throw new MenuException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        redisTemplate.opsForValue().set(JwtConstants.DETAILS_USER_ID+user.getId(),id,30, TimeUnit.MINUTES);
        return Result.success("选择成功");
    }

    @Override
    public Result menu() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        User user = (User) redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        if (user==null){
            throw new MenuException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        String roleId = (String) redisTemplate.opsForValue().get(JwtConstants.DETAILS_USER_ID + user.getId());
        if (StrUtil.isBlank(roleId)){
            throw new MenuException(LoginConstants.ERROR,LoginConstants.ERROR_MSG);
        }
        List<Menu>listResult=menuMapper.menu(roleId);
        List<Menu>list=digui(listResult,0);
        return Result.success(list);
    }

    private List<Menu> digui(List<Menu> data, int i) {
        List<Menu> objects = new ArrayList<>();
        for (Menu datum : data) {
            if (datum.getFid().equals(i)){
                List<Menu> digui = digui(data, datum.getId());
                datum.setMenus(digui);
                objects.add(datum);
            }
        }
        return objects;
    }
}
